package com.guigu.tomcat.impl;

import com.guigu.tomcat.Cookie;
import com.guigu.tomcat.HttpServletRequest;
import com.guigu.tomcat.HttpServletResponse;
import com.guigu.tomcat.ServletException;

import java.io.IOException;
import java.io.PrintWriter;

public class CookieServlet extends HttpServletImpl {
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        //获取浏览器发回给服务器的cookie数据
        Cookie[] cookies = request.getCookies();
        //输出cookie
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();
        out.println("<ul>");
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                //a=100
                String s = cookie.getName() + "=" + cookie.getValue();
                out.println("<li>" + s + "</li>");
            }
        }
        out.println("</ul>");

        //修改某个cookie值
        Cookie cookie = new CookieImpl("a", "200");
        response.addCookie(cookie);

        //删除cookie
        cookie = new CookieImpl("b", "200");
        cookie.setMaxAge(0);//设置有效期为0
        response.addCookie(cookie);

        //添加新的cookie有效期为一周
        String c =request.getParameter("c");
        cookie = new CookieImpl("c",c);
        cookie.setMaxAge(60*60*24*7);
        response.addCookie(cookie);
    }
    @Override
    public void init() {

    }

    @Override
    public void destroy() {

    }
}
